package com.demo.datastructure.stack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @description:
 * @author: ljr
 * @time: 2021/4/27 15:10
 */
public class MyCounter2 {

    public int calculate(String s) {
        int sign = 1;
        MyStack<Integer> intStack = new MyStack<>();
        intStack.push(1);
        int i = 0;
        int n = s.length();
        int result = 0;
        while(i < n){
            if (s.charAt(i) == ' ') {
                i++;
            }else if(s.charAt(i) == '+'){
                sign = intStack.peek();
                i++;
            }else if(s.charAt(i) == '-'){
                sign = -intStack.peek();
                i++;
            }else if(s.charAt(i) == '('){
                intStack.push(sign);
                i++;
            }else if(s.charAt(i) == ')'){
                intStack.pop();
                i++;
            }else{
                int num = 0;
                while(i < n && Character.isDigit(s.charAt(i))){
                    num = num*10+s.charAt(i)-'0';
                    i++;
                }
                result += sign * num;
            }
        }
        return result;
    }
    public static void main(String[] args) {
        MyCounter2 myCounter = new MyCounter2();
        int num = myCounter.calculate("1-(4+5+2+(2+2))-3+(6+8)");
        int num2 = 1-(4+5+2+(2+2))-3+(6+8);
        System.out.println(num2);
        System.out.println(num);

    }
    public int calculate2(String s) {
        Deque<Integer> ops = new LinkedList<Integer>();
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;
        while (i < n) {
            if (s.charAt(i) == ' ') {
                i++;
            } else if (s.charAt(i) == '+') {
                sign = ops.peek();
                i++;
            } else if (s.charAt(i) == '-') {
                sign = -ops.peek();
                i++;
            } else if (s.charAt(i) == '(') {
                ops.push(sign);
                i++;
            } else if (s.charAt(i) == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                    i++;
                }
                ret += sign * num;
            }
        }
        return ret;
    }
}
